package com.ym.domain.event;

import cn.hutool.core.net.NetUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.ym.domain.common.util.DateComUtil;
import com.ym.domain.common.util.RegionComUtil;
import com.ym.domain.common.util.SnowflakeIdWorker;
import com.ym.domain.common.util.StringComUtil;
import com.ym.domain.dao.LoginInfoService;
import com.ym.domain.model.LoginInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class LoginEventListener {

    @Autowired
    LoginInfoService loginInfoService;

    @Async
    @EventListener
    public void saveLoginInfo(LoginInfoEvent loginInfoEvent) {
        HttpServletRequest request = loginInfoEvent.getRequest();
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));

        String mobile = loginInfoEvent.getMobile();
        String roleType = loginInfoEvent.getRoleType();
        String ip = JakartaServletUtil.getClientIP(request);
        String browser = userAgent.getBrowser().getName();
        String os = userAgent.getOs().getName();
        String msg = loginInfoEvent.getMsg();
        String address = getRealAddressByIP(ip);

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(SnowflakeIdWorker.nextId());
        loginInfo.setMobile(mobile);
        loginInfo.setRoleType(roleType);
        loginInfo.setIp(ip);
        loginInfo.setLoginLocation(address);
        loginInfo.setBrowser(browser);
        loginInfo.setOs(os);
        loginInfo.setMsg(msg);
        loginInfo.setAccessTime(DateComUtil.getLocalDateTimeNow());
        loginInfoService.save(loginInfo);
    }

    private String getRealAddressByIP(String ip) {
        if (StringComUtil.isEmpty(ip)) {
            return "XX XX";
        }
        // 内网不查询
        ip = StringComUtil.contains(ip, "0:0:0:0:0:0:0:1") ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
        if (NetUtil.isInnerIP(ip)) {
            return "内网IP";
        }
        return RegionComUtil.getCityInfo(ip);
    }

}
